package com.jiang.剑指Offer.树.NC72;

import com.jiang.剑指Offer.树.TreeNode;

import java.util.Stack;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/01/02 22:41
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return TreeNode类
     */
    // 递归
    // public TreeNode Mirror (TreeNode pRoot) {
    //     // write code here
    //     if (pRoot == null) return null;
    //     TreeNode temp = pRoot.left;
    //     pRoot.left = pRoot.right;
    //     pRoot.right = temp;
    //     Mirror(pRoot.left);
    //     Mirror(pRoot.right);
    //     return pRoot;
    // }

    // 栈
    public TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if (pRoot == null) return null;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(pRoot);
        while (!stack.isEmpty()) {

            // 节点出栈
            TreeNode node = stack.pop();
            // 根节点的左右子树入栈
            if (node.left != null) stack.add(node.left);
            if (node.right != null) stack.add(node.right);
            // 左右子树交换
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return pRoot;
    }
}
